<?php

namespace backend\controllers;

use backend\models\JjrUser;
use backend\models\JjrUserCommission;
use Yii;
use backend\models\JjrUserProject;
use backend\models\JjrUserProjectSearch;
use backend\controllers\BaseController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use SimpleExcel\SimpleExcel;

/**
 * JjrUserProjectController implements the CRUD actions for JjrUserProject model.
 */
class JjrUserProjectController extends BaseController
{
    public $enableCsrfValidation = false;
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }
    public function actionSearch($q=''){
        $out = ['results' => ['id' => '', 'text' => '']];
        $query = JjrUserProject::find()->alias('up')
            ->leftJoin('yii2_jjr_project p','up.jjr_project_id=p.id')
            ->leftJoin('yii2_jjr_user u','u.id=up.jjr_user_id')
             ->orderBy(['up.update_time'=>SORT_DESC]);
        if($q){
            $query->andFilterWhere(['like', 'p.name', $q]);
        }
        $projects =  $query->select('up.id,u.real_name,p.name,up.client_real_name')->asArray()->all();
        foreach ($projects as &$project) {
            $project['text'] = "[{$project['name']}]经纪人:{$project['real_name']}客户:{$project['client_real_name']}";
        }
        $out['results'] = $projects;
        return $this->ajaxReturn($out);
    }

    /**
     * Lists all JjrUserProject models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new JjrUserProjectSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single JjrUserProject model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new JjrUserProject model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new JjrUserProject();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing JjrUserProject model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            //判断是否满足结佣
            $commission = JjrUserCommission::findOne(['jjr_user_id'=>$model->id]);

            if(!$commission){
                $user = JjrUser::findOne(['id'=>$model->jjr_user_id]);
                if($user->identity==JjrUser::IDENTITY_FREE&&$model->process>=JjrUserProject::PROCESS_PAY){
                    return $this->redirect(['/jjr-user-commission/create-self', 'userProjectId' => $model->id]);
                }else if($user->identity==JjrUser::IDENTITY_COMPANY&&$model->process>=JjrUserProject::PROCESS_CONTRACT){
                    return $this->redirect(['/jjr-user-commission/create-self', 'userProjectId' => $model->id]);
                }
            }

            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing JjrUserProject model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the JjrUserProject model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return JjrUserProject the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = JjrUserProject::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
    /**
     * excel导出
     */
    public function actionExport(){
        require_once('../../vendor/SimpleExcel/SimpleExcel.php');
        $excel = new SimpleExcel('CSV');
        $excel->writer->setDelimiter(",");
        $exportCustomer = [['id','客户姓名','客户手机','客户性别','项目进度','项目名称','经纪人','创建时间']];
        $query = JjrUserProject::find()->asArray()
            ->alias('up')
            ->leftJoin('yii2_jjr_project p','up.jjr_project_id=p.id')
            ->leftJoin('yii2_jjr_user u','up.jjr_user_id=u.id')
            ->select('up.status,u.real_name,up.client_gender,up.id,up.client_real_name,up.client_mobile,p.name,up.process,up.create_time,up.update_time');
        $customers = $query->all();
        foreach ($customers as $customer){
            $gender = $customer['client_gender']=='1'?'男':'女';
            $progressName = $this->getProcessName($customer);
            $tmp = [$customer['id'],$customer['client_real_name'],$customer['client_mobile']."\t",$gender,$progressName,$customer['name'],$customer['real_name'],$customer['create_time']];
            $exportCustomer[] = $tmp;
        }
        $excel->writer->setData (
            $exportCustomer);
        $excel->writer->saveFile ( '导出客户' );
    }

    public function getProcessName($model){
        if ($model['process'] == 1) {
            return "报备";
        } else if ($model['process'] == 2) {
            return "到访接待";
        } else if ($model['process'] == 3) {
            return "认筹认购";
        } else if ($model['process'] == 4) {
            return "签约";
        } else if ($model['process'] == 5) {
            return "结款";
        }
    }
}


